package netWork;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-10-13
 * Time: 17:23
 */
public class UdpEchoClient {
    //这里同样需要创建出一个DatagramSocket对象，后面网卡编程的基础
    private DatagramSocket socket = null;
    //服务端IP
    private String serverIp = "";
    //服务端端口
    private int serverPort = 0;

    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        //当创建DatagramSocket对象时，如果不传入参数的话，计算机就会自动分配未被占用的端口号
        socket = new DatagramSocket();
        //因为 UDP 在通信之前不需要建立连接，所以就需要我们主动添加目的IP和目的端口号
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("-->");
            //输入请求
            String request = scanner.next();
            //根据输入的请求创建数据报
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes("UTF-8"), request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);

            //发送请求
            socket.send(requestPacket);

            //创建接收响应的数据报
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);

            //将接收的二进制数据转换为字符串
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength(), "UTF-8");
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("192.168.144.1",9906);
        udpEchoClient.start();
    }
}
